'use strict';

const util = require("../../utils/config.js");
//index.js
//获取应用实例
const app = getApp()
const http_host = util.http_host;
const agent_id = util.agent_id;
const img_url = util.img_url;
const appId = util.appId;
const secret = util.secret;
// 创建页面实例对象
Page({
  data: {
    block: false,
    restaurant: false,
    check: true,
    //会员购买的商品
    MemberGoods: '',
    //图片全局地址
    ImgUrl:'',
    //当前商家的信息
    shopInfo:'',
    //当前商品的总餐盒费
    boxPrice: '',
    //当前用户的openId
    openId:'',
    //当前用户的选择地址
    defaultAddress: '',
    //当前预计收货的时间
    nowDate:'',
    //当前的总价格
    allMoney: '',
    //本来需要支付的总价格
    allPayMoney:'',
    //配送费
    servicePrice:'',
    //新用户立减
    newMemberPrice:'',
    //满减价格
    reducePrice:0,

    //为了退回设置的参数
    backShopId: '',
    backData : '',
    //优惠券的id和优惠券减免的价格
    lessenPrice: '0',
    lessenId:'',
    lessenPay:'',
    //备注信息
    cityDetail:'',
    //订单号存
    shopOrder: '',
    //是否为第二次消费
    shopDataAgain:'',
    //当前的id
    packages:'',
    //当前商家的agent_id是多少
    agent_id:'',
  },
  onLoad: function (id) {
  console.log(2)
  console.log(id)
  wx.getLocation({
    type: 'wgs84',
    success: function (res) {
      console.log(res)
      app.address.lat = res.latitude
      app.address.lng = res.longitude
       
    }
  })  
    var that = this;
    const openId = app.globalData.openId;
    app.globalData.goods = id.chooseGoods;

    app.globalData.shopId = id.shopId;
    that.setData({
      lessenPrice: 0,
      lessenPay: 0,
      allMoney:'',
      allPayMoney:'',
      shopDataAgain:id.again,
      agent_id: agent_id
    })
    var data = id.chooseGoods;    //选择了的商品
    var shopId = id.shopId;   //购买的当前商家
    var date = new Date();

    if(id.reduce){
      var reducePrice = id.reduce;
      that.setData({
        lessenPrice: -reducePrice,
        lessenId: id.lessen,    //优惠券的id
        lessenPay: reducePrice
      })
    }

    that.setData({
      backShopId: shopId,
      backData: data,
    })
    //获取当前的店铺信息
    wx.request({
      url: http_host + 'getNowShops',
      data: {
        id: shopId,
        openId:openId
      },
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        if(app.globalData.is_free==true){
            var reduce = 0;
        }else{
          var reduce = res.data.business_service_price;
        }

        that.setData({
          shopInfo: res.data,
          servicePrice: reduce,
          newMemberPrice: res.data.business_member_price
        })

        var price = 0;

        if (id.a == 1) {
          
        var os = 1
        
        var   ordershop = 'order_shop'
        
        } else{

        var   ordershop = 'getGoodsArray'
      
      }

     

        //获取当前收到的商品
        wx.request({
          url: http_host + ordershop,
          data: {
            data: app.globalData.order,
           
            shopid: id.shopId,
            oid:id.again
          },
          header: {
            'Content-Type': 'application/json'
          },
          success: function (res) {
            console.log('haha')
            console.log(res.data)

            that.setData({
              MemberGoods: res.data,
              ImgUrl: img_url
            })
            //当前用户的总价格
            var demo = res.data;
         
            //当前购买的价格
            for (var index in demo) {
              price += demo[index].menu_side_price * demo[index].count;
              
            }
            
            var jiage = price.toFixed(2)
            that.setData({
              allMoney: jiage,
              allPayMoney: jiage,
            })
            //获取满减下单立减的金额
            wx.request({
              url: http_host + 'getReducePrice',
              data: {
                price: price,
                shopId: shopId
              },
              header: {
                'Content-Type': 'application/json'
              },
              success: function (res) {
                var result = that.data.allMoney;
            
                result -= res.data.reduce;
                var newPrice = that.data.newMemberPrice;
                var nowPrice = newPrice + res.data.reduce;

                var demoPay = that.data.lessenPay;

                nowPrice += parseInt(demoPay);
              
                that.setData({
                  allMoney: result,
                  reducePrice: nowPrice
                })
                //2
                //获取当前用户的收货地址
                wx.request({
                  url: http_host + 'getDefaultAddress',
                  data: {
                    openId: openId
                  },
                  header: {
                    'Content-Type': 'application/json'
                  },
                  success: function (res) {
                    that.setData({
                      defaultAddress: res.data
                    })
                  }
                })
                //获取当前订单的餐盒费      
                wx.request({
                  url: http_host + 'getBoxPrice',
                  data: {
                    data: app.globalData.order,

                    shopid: id.shopId,
                  },
                  header: {
                    'Content-Type': 'application/json'
                  },
                  success: function (res) {
                    if(app.globalData.is_free==true){
                      var box = 0;
                    }else{
                      var box = res.data;
                    }
                    that.setData({
                      boxPrice: box
                    })

                    var qian = that.data.allMoney;  //需要支付的
                    var peisong = that.data.servicePrice; //配送费
                    var all = qian + box   //需要支付的加上餐盒费
                    var needPay = qian + peisong + res.data;
                    that.setData({
                      allPayMoney: needPay
                    })
                    all += peisong;

                    var newMember = that.data.newMemberPrice;
                    var reduce = that.data.reducePrice;
                    reduce+=newMember;
                    // var unadd = that.data.reducePrice;
                    // console.log(unadd);
                    // var allAdd = unadd + newMember;
                    //查看是否有优惠券
                    var lessenPay = that.data.lessenPay;

                    all -= lessenPay;
                    all -= newMember;

                    if(all<0){
                      all = 0.01
                    }
                    that.setData({
                      allMoney: all,
                     // allMoney: 0.01,
                      reducePrice: reduce
                    })
                  }
                })
              }
            })
          }
        })


      }
    })



    //计算到达时间
    function CurentTime() {
      var now = new Date();

      var hh = now.getHours() + 1;            //时
      var mm = now.getMinutes();          //分


      var clock = '';

      if (hh < 10)
        clock += "0";

      clock += hh + ":";
      if (mm < 10) clock += '0';
      clock += mm;

      return (clock);
    }
    that.setData({
      nowDate: CurentTime()
    })
  },
  calling: function () {
    wx.makePhoneCall({
      phoneNumber: this.data.shopInfo.business_tel,
      success: function () {
        console.log("拨打电话成功！")
      },
      fail: function () {
        console.log("拨打电话失败！")
      }
    })
  },
  Block: function () {
    this.setData({
      block: true
    })
  },
  takeOut: function () {
    this.setData({
      restaurant: false
    })
  },
  Cancel: function () {
    this.setData({
      block: false,
      check: true,
      restaurant: false
    })
  },
  Ok: function () {
    var that = this;
    this.setData({
      block: false,
    })
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        console.log(res);
        that.setData({
          restaurant: true
        })
      },
      fail: (res) => {
        that.setData({
          restaurant: false,
          check: true
        });
      }
    })
  },
  toMyPackage: function () {
    wx.navigateTo({
      url: '../useroperation/useroperation?operation=myPackage',
    })
  },
  toMyCoupon: function () {
    var that = this;
    var backShop = that.data.backShopId;
    var backData = that.data.backData;
    var allPay = that.data.allPayMoney;
    wx.navigateTo({
      url: '../useroperation/useroperation?operation=coupon&type=reduce&shopId=' + backShop +"&pay="+ allPay + "&shopData=" + backData,
    })
  },
  toMyAddress: function () {
    var that = this;
    var openId = app.globalData.openId;
    var backShop = that.data.backShopId;
    var backData = that.data.backData;
    wx.navigateTo({
      url: '../useroperation/useroperation?operation=address&openId=' + openId + "&shopId=" + backShop + "&shopData=" + backData,
    })
  },
  //设置备注值
  setCityDetail: function (e) {
    this.setData({
      cityDetail: e.detail.value
    })
  },
  submitOrders: function (e) {

    var that = this;

    
    var openId = app.globalData.openId;
    //需要支付的价格
    var payMoney = that.data.allMoney;
    //发起支付请求

    wx.request({
      url: http_host + 'Pay',
      data: {
        agent_id : agent_id,
        openId: openId,
        total_fee: payMoney //充值多少
        //total_fee: 0.01
      },
      success:function (res) {
  
        var order = res.data.out_trade_no;
      
        that.setData({
          packages: res.data['package']
        })


        if(res.data){
          
          var shop = that.data.MemberGoods
          var s = []
          var snumber = []
        
          for (var i = 0; i < shop.length;i++)
          {

     
              snumber[i] = shop[i].count
              s[i] = shop[i].id
          }
    
          // out_trade_no = res.data['out_trade_no'];
          wx.requestPayment({
            timeStamp: res.data['timeStamp'],
            nonceStr: res.data['nonceStr'],
            package: res.data['package'],
            signType: 'MD5',
            paySign: res.data['paySign'],
            success:function(res){

              //添加订单
              var again = that.data.shopDataAgain;

              var shopId = that.data.backShopId;    //当前购买的商家

              var shopData = that.data.backData;    //当前购买的所有商品

              var lessen_id = that.data.lessenId;   //当前购买使用的优惠券id

              var openId = that.data.defaultAddress.openId; //用户的openId

              var address = that.data.defaultAddress.id;    //当前购买的地址

              var allPrice = that.data.allMoney;    //当前购买的价格

              var remarks = that.data.cityDetail; //备注信息

              var reducePrice = that.data.reducePrice;  //优惠的金额

              var allPayMoney = that.data.allPayMoney;  //总共的价格

              var access_token = app.globalData.accessToken.access_token;    //当前的access_token

              var packages = e.detail.formId;

              var agent_id = that.data.agent_id;

        
              wx.request({
                url: http_host + 'putOrder',
                data: {
                  //用户经纬度
                  lat: app.address.lat,
                  lng: app.address.lng,
                  //唯一标识
                  agent_id:agent_id,
                  //商品id
                  order_static:2,
                  openId: openId,    //用户的openid
                  shopId: shopId,    //购买的商家
                  order: order, //订单号
                  address: address, //购买的地址
                  shopData: shopData,   //当前购买的商品
                  allPrice: allPrice,   //当前购买的总价格
                  lessen_id: lessen_id,    //当前购买使用的优惠券,
                  remarks: remarks,      //改商品的备注信息
                  status: 1,     //当前是订单的状态
                  again: again,   //第二次提交
                  reducePrice: reducePrice,  //优惠的金额
                  allPayMoney: allPayMoney,    //总共的价格
                  access_token: access_token,   //当前的access_token
                  packages: packages,    //当前的packages
                  shangpin: s,
                  shangpinshu: snumber,
                  zhifustatic:1,
                },
                header: {
                  'Content-Type': 'application/json'
                },
                success: function (res) {
                  console.log('成功')
                  console.log(res.data);
                  wx.reLaunch({
                    url: '../myOrder/myOrder'
                  })
                }
              })
          },
            fail:function(res){


              console.log(3)
              console.log(e.detail.formId)
              //添加订单
              var again = that.data.shopDataAgain;

              var shopId = that.data.backShopId;    //当前购买的商家

              var shopData = that.data.backData;    //当前购买的所有商品

              var lessen_id = that.data.lessenId;   //当前购买使用的优惠券id

              var openId = that.data.defaultAddress.openId; //用户的openId

              var address = that.data.defaultAddress.id;    //当前购买的地址

              var allPrice = that.data.allMoney;    //当前购买的价格

              var remarks = that.data.cityDetail; //备注信息

              var reducePrice = that.data.reducePrice;  //优惠的金额

              var allPayMoney = that.data.allPayMoney;  //总共的价格

              var access_token = app.globalData.accessToken.access_token;    //当前的access_token

              var packages = e.detail.formId;

              var agent_id = that.data.agent_id;
             // console.log(s)
              wx.request({
                url: http_host + 'putOrder',
                data: {
                  //用户经纬度
                  lat: app.address.lat,
                  lng: app.address.lng,
                  //唯一标识
                  agent_id: agent_id,
                  //商品id
                  order_static:2,
                  openId: openId,    //用户的openid
                  shopId: shopId,    //购买的商家
                  order: order, //订单号
                  address: address, //购买的地址
                  shopData: shopData,   //当前购买的商品
                  allPrice: allPrice,   //当前购买的总价格
                  lessen_id: lessen_id,    //当前购买使用的优惠券,
                  remarks: remarks,      //改商品的备注信息
                  status: 2,     //当前是订单的状态
                  again: again,   //第二次提交
                  reducePrice: reducePrice,  //优惠的金额
                  allPayMoney: allPayMoney,    //总共的价格
                  access_token: access_token,
                  packages: packages,
                  shangpin: s,
                  shangpinshu:snumber,
                  zhifustatic:2,
                },
                header: {
                  'Content-Type': 'application/json'
                },
                success: function (res) {
                  console.log('失败')
                  console.log(res)
                  // wx.reLaunch({
                  //   url: '../index/index'
                  // })
                }
              })
            }
          })
        }
      },
      fail:function(){
        console.log('错')
      },
      complete:function(){

      }
    })
  }
})